﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace SlamCms.SharePoint.Migration
{
	public class MigratableListItem : IMigratable
	{
		public Dictionary<string, object> FieldValues { get; set; }
		public string SlamId { get; set; }
		public int ListRelativeId { get; set; }

		public MigratableListItem()
		{
			FieldValues = new Dictionary<string, object>();
		}

		public virtual XElement ToXml()
		{
			XElement listItemElement = new XElement("ListItem");
			listItemElement.Add(new XAttribute("ListRelativeId", ListRelativeId));
			if (!String.IsNullOrEmpty(SlamId))
				listItemElement.Add(new XAttribute("SlamId", SlamId));
			XElement fieldValuesElement = new XElement("FieldValues");
			foreach (var fieldValue in FieldValues)
			{
				XElement fieldValueElement = new XElement("FieldValue");
				fieldValueElement.Add(new XAttribute("Name", fieldValue.Key));
				if (fieldValue.Value != null)
					fieldValueElement.Add(new XAttribute("Value", fieldValue.Value));
				fieldValuesElement.Add(fieldValueElement);
			}
			listItemElement.Add(fieldValuesElement);
			return listItemElement;
		}

		public virtual void FromXml(XElement element)
		{
			ListRelativeId = int.Parse(element.Attribute("ListRelativeId").Value);
			if (element.Attribute("SlamId") != null)
				this.SlamId = element.Attribute("SlamId").Value;
			if (element.Element("FieldValues") != null)
			{
				foreach (XElement fieldValueElement in element.Element("FieldValues").Elements())
				{
					if (fieldValueElement.Attribute("Value") != null)
						FieldValues.Add(fieldValueElement.Attribute("Name").Value, fieldValueElement.Attribute("Value").Value);
				}
			}
		}
	}
}
